package db

import (
	"database/sql"
	"fmt"
)

//GetAll ...
func GetAll(rows *sql.Rows) (res map[int][]string) {
	res = make(map[int][]string)

	if rows == nil {
		return nil
	}
	cols, err := rows.Columns()
	rawResult := make([][]byte, len(cols))
	result := make([]string, len(cols))
	dest := make([]interface{}, len(cols))
	for i, _ := range rawResult {
		dest[i] = &rawResult[i]
	}
	x := 0
	for rows.Next() {
		err = rows.Scan(dest...)

		for i, raw := range rawResult {
			if raw == nil {
				result[i] = ""
			} else {
				result[i] = string(raw)
			}
		}
		res[x] = result
		x++
	}
	_ = err
	return

}
//GetOne ...
func GetOne(rows *sql.Rows) []string {
	if rows == nil {
		return nil
	}
	cols, err := rows.Columns()
	rawResult := make([][]byte, len(cols))
	result := make([]string, len(cols))
	dest := make([]interface{}, len(cols))
	for i, _ := range rawResult {
		dest[i] = &rawResult[i]
	}
	if rows.Next() {
		err = rows.Scan(dest...)

		for i, raw := range rawResult {
			if raw == nil {
				result[i] = ""
			} else {
				result[i] = string(raw)
			}
		}
	} else {
		return nil
	}
	_ = err
	return result
}

func GetKeyValuesAll(rows *sql.Rows) ([]map[string]interface{}, error) {
	columns, err := rows.Columns()
	if err != nil {
		fmt.Println("rows.Columns() -> " + err.Error())
		return nil, err
	}
	scanArgs := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	record := []map[string]interface{}{}
	for rows.Next() {
		//将行数据保存到record字典
		err = rows.Scan(scanArgs...)
		record = append(record, make(map[string]interface{}))
		for i, val := range values {
			if val != nil {
				switch val.(type) {
				case int64:
					record[len(record)-1][columns[i]] = val
				default:
					record[len(record)-1][columns[i]] = string(val.([]byte))
				}
			} else {
				record[len(record)-1][columns[i]] = ""
			}
		}
	}
	return record, nil
}

func GetKeyValuesOne(rows *sql.Rows) (map[string]interface{}, error) {
	columns, err := rows.Columns()
	if err != nil {
		fmt.Println("rows.Columns() -> " + err.Error())
		return nil, err
	}
	scanArgs := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	record := map[string]interface{}{}
	if rows.Next() {
		//将行数据保存到record字典
		err = rows.Scan(scanArgs...)
		for i, val := range values {
			if val != nil {
				switch val.(type) {
				case int64:
					record[columns[i]] = val
				default:
					record[columns[i]] = string(val.([]byte))
				}
			} else {
				record[columns[i]] = ""
			}
		}
	}
	return record, nil

}

